require([
    'jquery',
    'lodash',
    'backbone',
    'views/listing-details',
    'views/listing-list',
    'utils/tpl',
    'models/listing-model',
    'models/listing-collection'
],

function($, _, Backbone, ListingView, ListingListView, tpl, Listing, ListingCollection) {

    Backbone.View.prototype.close = function() {
        console.log('Closing view ' + this);
        if (this.beforeClose) {
            this.beforeClose();
        }
        this.remove();
        this.unbind();
    };

    var AppRouter = Backbone.Router.extend({

        initialize: function() {
            
        },

        routes: {
            "": "list",
            "listings/new": "newListing",
            "listings/:id": "listingDetails"
        },

        list: function() {
            this.before(function() {
                
            });
        },

        listingDetails: function(id) {
            this.before(function() {
                var listing = this.listingList.get(id);
                this.showView('#content', new ListingView({
                    model: listing
                }));
            });
        },

        newListing: function() {
            this.before(function() {
                this.showView('#content', new ListingView({
                    model: new Listing()
                }));
            });
        },

        showView: function(selector, view) {
            if (this.currentView) this.currentView.close();

            $(selector).html(view.render());
            this.currentView = view;

            return view;
        },

        before: function(callback) {
            if (this.listingList) {
                if (callback) callback.call(this);
            } else {
                this.listingList = new ListingCollection();
                var self = this;
                this.listingList.fetch({
                    success: function() {
                        var listingList = new ListingListView({
                            model: self.listingList
                        }).render();
                        $('#sidebar').html(listingList);
                        if (callback) callback.call(self);
                    }
                });
            }
        }

    });

    tpl.loadTemplates(['listing-details', 'listing-list-item'], function() {
        window.app = new AppRouter();
        Backbone.history.start();
    });

}); // End require
